﻿using FileTransfer.Assistantor;
using HAF.FtpUtility;
using HAF.FtpUtility.Model;
using HAF.LogUtility;
using HAF.NetUtility.Assistantor;
using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace FileTransfer
{
    public partial class FrmSiteMain : Form
    {
        private string AppName = "FTP客户端";
        private string AppVersion = "Ver3.1";

        public FrmSiteMain()
        {
            InitializeComponent();
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            ShowClear();
            if (string.IsNullOrEmpty(txtUrl.Text))
            {
                ShowPopTips("请输入请求FTP地址");
                return;
            }

            if (cmbFtpType.SelectedIndex == 0)
            {
                ShowMessage("将使用FluentFtp进行下载");
                DownFluentThread(txtUrl.Text.TrimEnd());
            }
            else
            {
                ShowMessage("将使用FtpWebRequest进行下载");
                DownFtpWebThread(txtUrl.Text.TrimEnd());
            }
        }

        private void DownFluentThread(string ftpurl)
        {
            SiteTaskConfig siteConfig = FtpUrlParser.ParseFtpUrl(txtUrl.Text);
            if (siteConfig != null)
            {
                string localfile = Path.Combine(LoadContext.AppPath, "Down", siteConfig.FileSets[0].FileName);
                ShowMessage(string.Concat("本地存储目录为", localfile));
                using (FluentFtpHelper ftpClient = new FluentFtpHelper(siteConfig))
                {
                    ftpClient.LogOutName = string.Format("{0}{1}", siteConfig.ID, DateTime.Now.Ticks);
                    ftpClient.WriteConsoleMessageEvent = ShowMessage;
                    ftpClient.DownFile(localfile, siteConfig.FileSets[0].RemoteFileName);
                }
            }
        }

        private void DownFtpWebThread(string ftpurl)
        {
            SiteTaskConfig siteConfig = FtpUrlParser.ParseFtpUrl(txtUrl.Text);
            string localfile = Path.Combine(LoadContext.AppPath, "Down", siteConfig.FileSets[0].FileName);
            ShowMessage(string.Concat("本地存储目录为", localfile));
            using (FtpAssistantor ftpClient = new FtpAssistantor(siteConfig))
            {
                ftpClient.LogOutName = string.Format("{0}{1}", siteConfig.ID, DateTime.Now.Ticks);
                ftpClient.WriteConsoleMessageEvent = ShowMessage;
                ftpClient.Download(localfile, siteConfig.FileSets[0].RemoteFileName);
            }
        }

        #region baseFunction
        private void ShowPopTips(string message)
        {
            MessageBox.Show(message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        int _msgLen = 0;

        private void ShowClear()
        {
            txtMsg.Clear();
        }

        private void ShowMessage(string msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(ShowMessage), msg);
            }
            else
            {
                if (_msgLen >= 300)
                {
                    txtMsg.Clear();
                    //txtMessages.Text = "";
                    _msgLen = 0;
                }
                LogHelper.WriteDebugLogExt("SysMonitor", msg);

                txtMsg.Text = txtMsg.Text + (DateTime.Now.ToString() + " " + msg + "\r\n");
                txtMsg.SelectionStart = txtMsg.Text.Length;
                txtMsg.ScrollToCaret();

                _msgLen++;

            }
        }
        #endregion baseFunction

        private void FrmSiteMain_Load(object sender, EventArgs e)
        {
            this.Text = string.Concat(AppName, AppVersion);

            cmbFtpType.SelectedIndex = 0;
            txtProcessCaption.Visible = false;
            processBar.Visible = false;

            if (!FileAssistantor.IsLinkExists("PandaTransfer", System.Environment.CurrentDirectory))
            {
                FileAssistantor.CreateNewDesktopShortcut("PandaTransfer", Path.Combine(System.Environment.CurrentDirectory, "PandaTransfer.exe"), true);
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            txtUrl.Clear();
        }

        private void btnCheckNet_Click(object sender, EventArgs e)
        {
            var runCfg = GetFtpConfig(txtUrl.Text);
            ShowMessage(string.Format("开始检测{0}的可访问性", runCfg.ToString()));
            Thread thread = new Thread(delegate ()
            {
                string rtnStr = CmdAssistant.GetInstance().Ping(runCfg.Host);
                ShowMessage(rtnStr);

                bool rtn = CmdAssistant.GetInstance().Telnet(runCfg.Host, runCfg.Port);
                ShowMessage(string.Format("telnet {0} {1} {2}", runCfg.Host, runCfg.Port, rtn ? "成功" : "失败"));
            })
            { Name = "checkThread", IsBackground = true, Priority = ThreadPriority.Normal };
            thread.Start();
        }

        private SiteTaskConfig GetFtpConfig(string url)
        {
            ShowClear();
            var runFtpConfig = FtpUrlParser.ParseFtpUrl(url);
            if (runFtpConfig != null)
            {

            }

            return runFtpConfig;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }
    }
}
